/*
 *  Class name: BookPropertyEditor.java
 *  Version: 1.0
 *  Date: 23.6.2014
 */
package cz.morosystems.personwebmanager.presentationlayer.propertyeditors;

import cz.morosystems.personwebmanager.businesslayer.sevices.BookService;
import cz.morosystems.personwebmanager.persistencelayer.entities.Book;
import java.beans.PropertyEditorSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author Michal Ďuriš
 */
@Component
public class BookPropertyEditor extends PropertyEditorSupport {

    @Autowired
    private BookService bookService;

    public BookPropertyEditor() {
    }

    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }
    
    @Override
    public void setAsText(String text) throws IllegalArgumentException {

        if (text == null || text.isEmpty()) {
            setValue(null);
        }
        
        try {

            Long id = Long.parseLong(text);
            setValue(bookService.getBookByID(id));
            
        } catch (NumberFormatException ex) {
            setValue(null);
        }
    }

    @Override
    public String getAsText() {
        
        if(getValue() == null) {
            return "";
        }
        
        return Long.toString(((Book) getValue()).getId());
    }

}
